package com.baidu.aip.unit;

import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.TimeoutException;

import com.baidu.aip.unit.exception.UnitError;
import com.baidu.aip.unit.listener.OnResultListener;
import com.baidu.aip.unit.model.Scene;
import com.baidu.aip.unit.model.response.Action;
import com.baidu.aip.unit.model.response.CommunicateResponse;
import com.baidu.aip.unit.model.response.HintQuery;
import com.baidu.aip.unit.utils.TextUtils;

/**
 * 这是一个在命令行下执行的UNIT交互程序
 * @author hling
 *
 */
public class CmdLineChat {
	
	private static final int SCENE_SWEEPER_ROBOT = 3087;
	
	public static void main(String[] args) throws UnitError, TimeoutException {
        
        String appKey = "jMWIPDmK6zaxiK9KMCbb0hQl";
    	String secretKey = "D4d5DD51gElVGkoHuoOZZfSHFDDT5K5k";
    	// 演示数据，开发者可到ai.baidu.com 官网理解与交互技术(UNIT)板块申请并训练自己的场景机器人
    	Scene scene = new Scene(SCENE_SWEEPER_ROBOT , "扫地机器人");
    	
    	if (args.length == 3) {
    		appKey = args[0];
    		secretKey = args[1];
    		scene = new Scene(Integer.parseInt(args[2]), "自己的机器人");
    		
    		System.out.println("当前使用传入参数的场景，场景ID:" + args[2]);
    	} else {
    		System.out.println("当前使用内置百度官方UNIT机器人。如果要使用自己的UNIT，请在命令行中依次添加三个参数:API Key、Secret Key、Unit Scene ID");
    		System.out.println("例： java -jar unitsdk.jar jMWIPDmK6zaxiK9KMCbb0hQl D4d5DD51gElVGkoHuoOZZfSHFDDT5K5k 3087");
    	}
    	
        System.out.println("正在获取Token...");
    	UnitBot bot = new UnitBot();
    	bot.initAccessToken(appKey, secretKey);
    	System.out.println("获取Token完毕。现在你可以在控制台输入指令，按回车键发送。");
    	System.out.println("输入exit退出程序。\r\n");
    	bot.setScene(scene);
    	
    	bot.setResponseListener(new OnResultListener<CommunicateResponse>() {

			@Override
			public void onResult(CommunicateResponse result) {
				SimpleResponseWrapper wrapper = new SimpleResponseWrapper(result);
				System.out.println(wrapper.toString());
				
				if (result.getActionList().size() > 0) {
					for (Action action : result.getActionList()) {
						if (!TextUtils.isEmpty(action.getSay())) {
							System.out.println("机器人说：" + action.getSay());
			            } else { 
							System.out.println("机器人调用函数：" + action.getMainExe());
			            }
		                for (HintQuery hint : action.getHintList()) {
		                	System.out.println("          " + hint.getHintQuery());
		                }
					}
				} else {
					System.out.println("机器人收到了你的指令，但什么也没说...");
				}
			}

			@Override
			public void onError(UnitError error) {
				System.out.println("机器人出错：" + error.getErrorMessage());
			}
    	});
    	
    	
        do {
        	String msg = readLine("我说：").trim();
        	if ("".equals(msg)) {
        		continue;
        	}
        	
        	if ("exit".equalsIgnoreCase(msg)) {
        		System.out.println("系统：接收到退出指令，程序退出。");
        		System.exit(0);
        		break;
        	}
        	
        	bot.sendMessageAndWait(msg);
        } while(true);
	}
	
	/**
	 * 读取控制台输入
	 * @param prompt
	 * @return
	 */
	private static String readLine(String prompt) {
        String line = null;
        Console c = System.console();
        if (c != null) {
             line = c.readLine(prompt);
        } else {
            System.out.print(prompt);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            try {
                 line = bufferedReader.readLine();
            } catch (IOException e) { 
                //Ignore
            }
        }
        return line;
    }
}
